#include <dbg.h>

#include <cassert>
using namespace std;

class Solution {
public:
    long long countSubarrays(vector<int>& nums, int k) {
        int maxVal = *max_element(nums.begin(), nums.end());
        long long res = 0;
        int cntMax = 0;
        int left = 0;
        for (int right = 0; right < nums.size(); ++right) {
            cntMax += nums[right] == maxVal;
            while (cntMax == k) {
                cntMax -= nums[left] == maxVal;
                ++left;
            }
            res += left;
        }
        return res;
    }
};

int main() {
    Solution s;

    vector<int> nums1{1, 3, 2, 3, 3};
    vector<int> nums2{1, 4, 2, 1};

    assert(s.countSubarrays(nums1, 2) == 6);
    assert(s.countSubarrays(nums2, 3) == 0);

    return 0;
}